package com.zh.note.demo.java8;

import lombok.Getter;
import lombok.Setter;

import java.util.Arrays;
import java.util.List;
import java.util.Optional;

/**
 * Optional.of(); Optional.ofNullable(); Optional.empty();
 */
public class OptionalDemo {
    public String getCity(User user) throws Exception {
        if (user != null) {
            if (user.getAddress() != null) {
                Address address = user.getAddress();
                if (address.getCity() != null) {
                    return address.getCity();
                }
            }
        }
        throw new Exception("取值错误");
    }

    public String getCity2(User user) throws Exception {
        return Optional.ofNullable(user).map(u -> u.getAddress())
                .map(a -> a.getCity())
                .orElseThrow(() -> new Exception("取指错误"));
    }

    public static void main(String[] args) {
        List<String> stringList = Arrays.asList("1", "2", "3");
        Optional<Object> empty = Optional.empty();

        // empty.orElse();
        // empty.orElseGet()

        Optional.of("a");
        Optional.ofNullable("ok");

    }

    @Setter
    @Getter
    private static class User {
        private Integer id;
        private String name;
        private Address address;
    }

    @Getter
    @Setter
    static class Address {
        private String City;
    }
}
